﻿using EMall.Application;
using EMall.ProductService.Products;
using EMall.Query;
using EMall.Uow;

namespace EMall.ProductService.ProductSkus
{
    public class ProductSkuAppService : ApplicationService, IProductSkuAppService
    {
        private readonly IProductSkuRepository _productSkuRepository;
        private readonly IProductRepository _productRepository;
        public ProductSkuAppService(
            IProductSkuRepository productSkuRepository,
            IProductRepository productRepository)
        {
            _productSkuRepository = productSkuRepository;
            _productRepository = productRepository;
        }
        [UnitOfWork]
        public async Task CreateAsync(CreateProductSkuDto input)
        {
            var product = await _productRepository.GetAsync(input.ProductId);
            var productSku = new ProductSku(input.ProductId, input.Spec, input.CostPrice, input.SalePrice, input.DefaultStock);
            await _productSkuRepository.AddAsync(productSku);
        }
        [UnitOfWork]
        public async Task UpdateAsync(UpdateProductSkuDto input)
        {
            var productSku = await _productSkuRepository.GetAsync(input.Id);
            productSku.Update(input.Spec, input.CostPrice, input.SalePrice);
        }
        [UnitOfWork]
        public async Task AddStockAsync(AddProductSkuStock input)
        {
            var productSku = await _productSkuRepository.GetAsync(input.Id);
            productSku.AddStock(input.Stock);
        }
        [UnitOfWork]
        public async Task RemoveStockAsync(RemoveProductSkuStock input)
        {
            var productSku = await _productSkuRepository.GetAsync(input.Id);
            productSku.RemoveStock(input.Stock);
        }
        public async Task<ProductSkuDto> GetAsync(int id)
        {
            var productSku = await QueryService.GetAsync<ProductSku, int>(id);
            return Mapper.Map<ProductSkuDto>(productSku);
        }
        public async Task<IPagedList<ProductSkuListDto>> GetPagedListAsync(GetProductSkuPagedListQueryDto input)
        {
            var pagedData = await QueryService.GetQueryable<ProductSku>()
               .Sorting(input.Sorting)
               .ToPagedListAsync(input.PageIndex, input.PageSize);
            return Mapper.Map<ProductSku, ProductSkuListDto>(pagedData);
        }
    }
}